﻿using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Tokens;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.WareHouser;

namespace SmartProduction.Read.API.Application.CommandHandlers.WareHouses
{
    /// <summary>
    /// 仓库管理查询命令处理
    /// </summary>
    public class WareHouseQueryCommandHandler:IRequestHandler<WareHouseQueryCommand,APIResult<APIPaing<WareHouse>>>
    {
        /// <summary>
        /// 仓库仓储
        /// </summary>
        private readonly IBaseRepository<WareHouse> wareRep;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="wareRep">仓库仓储</param>
        public WareHouseQueryCommandHandler(IBaseRepository<WareHouse> wareRep)
        {
            this.wareRep = wareRep;
        }

        public async Task<APIResult<APIPaing<WareHouse>>> Handle(WareHouseQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<WareHouse>> result = new APIResult<APIPaing<WareHouse>>();

            var lists = wareRep.GetAll().Result.Where(x => x.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.WareHouseName))
            {
                lists = lists.Where(x => x.WareHouseName.Contains(request.WareHouseName));
            }
            if (!string.IsNullOrEmpty(request.IsStauts))
            {
                lists = lists.Where(x => x.IsStauts.ToString()==(request.IsStauts));
            }

            int totalcount=lists.Count();
            int totalpage =(int) Math.Ceiling(totalcount * 1.0 / request.size);
            var pagelist = lists.OrderByDescending(x => x.WareHouseId).Skip((request.index - 1) * request.size).Take(request.size);


            APIPaing<WareHouse> page = new APIPaing<WareHouse>();

            page.TotalCount = totalcount;
            page.PageCount = totalpage;

            page.Items = pagelist.ToList();
            result.data= page;

            return await Task.FromResult(result);
        }
    }
}
